package com.wtwd.campus.service.impl;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.dao.DeviceInfoMapper;
import com.wtwd.campus.dao.H5Mapper;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.entity.H5Customer;
import com.wtwd.campus.entity.H5User;
import com.wtwd.campus.service.DeviceFlagService;
import com.wtwd.campus.service.H5Service;
import com.wtwd.campus.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author ldaoliang
 * @Date create in 14:14 2021/7/16
 * @Description
 */
@Service
public class H5ServiceImpl implements H5Service {

    @Resource
    private H5Mapper h5Mapper;
    @Resource
    private DeviceInfoMapper deviceInfoMapper;
    @Autowired
    private RedisService redisService;
    @Resource
    private DeviceFlagService deviceFlagService;

    private static final Logger logger = LoggerFactory.getLogger(H5ServiceImpl.class);

    @Override
    public H5Customer getH5CustomerByAppKey(String appKey) {
        return h5Mapper.getH5CustomerByAppKey(appKey);
    }

    @Override
    public int addH5UserIfAbsent(int h5CustomerId, String userId) {
        H5User h5User = h5Mapper.getH5UserByCustomerIdAndUserId(h5CustomerId, userId);
        // 用户不存在，添加
        if (h5User == null) {
            h5User = new H5User(h5CustomerId, userId, System.currentTimeMillis());
            h5Mapper.addH5User(h5User);
        }
        return h5User.getH5UserId();
    }

    @Override
    public List<Integer> deviceIdList(int h5UserId) {
        return h5Mapper.getH5DeviceList(h5UserId);
    }

    @Override
    public List<Map<String, Object>> deviceList(int h5UserId) {
        List<Map<String, Object>> deviceList = h5Mapper.getH5UserDeviceList(h5UserId);
        List<String> imeis = deviceList.stream().map(e -> (String) e.get("imei")).collect(Collectors.toList());
        if (deviceList != null && deviceList.size() > 0) {
            Map<String, Boolean> stringBooleanMap = deviceFlagService.bathGetDeviceOnline(imeis);
            deviceList.stream().forEach(map -> {
                        boolean isOnline = stringBooleanMap.get((String) map.get("imei"));
                        map.put("isOnline", isOnline);
                        String sim_card = this.filterPhone((String) map.get("sim_card"), "+86");
                        map.put("sim_card", sim_card);
                    }
            );
        }
        return deviceList;
    }


    /**
     * 校验手机号是否含有前缀
     * 如果含有这个前缀去掉
     *
     * @param phone
     * @param sign
     * @return
     */
    private String filterPhone(String phone, String sign) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(sign)) {
            return phone;
        }
        if (phone.startsWith(sign)) {
            phone = phone.substring(sign.length());
        }
        return phone;
    }


    /**
     * 判断设备是否在线
     *
     * @param imei 设备imei号
     * @return 设备是否在线
     */
    public boolean deviceOnline(String imei) {
        boolean isOnline = redisService.hasKey(Constants.DEVICE_ONLINE_PREFIX + imei);
        logger.info("设备:【{}】: {}", imei, isOnline ? "在线" : "离线");
        return isOnline;
    }

    @Override
    public RespEntity bindDevice(int h5UserId, String imei, String studentName) {
        // 校验设备是否存在
        DeviceInfo deviceInfo = deviceInfoMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return new RespEntity(RespCode.DEVICE_NOT_FOUND);
        }
        if (deviceInfo.getDeviceType() != Constants.H5_DEVICE) {
            return new RespEntity(RespCode.NOT_H5_DEVICE_CANNOT_BIND);
        }
        Integer deviceId = deviceInfo.getDeviceId();
        List<Integer> deviceIdList = h5Mapper.getH5DeviceList(h5UserId);
        if (deviceIdList != null && deviceIdList.size() > 0) {
            // 校验是否重复绑定
            for (Integer id : deviceIdList) {
                if (id.equals(deviceId)) {
                    return new RespEntity(RespCode.REPEAT_BINDING);
                }
            }
        }
        int i = h5Mapper.addBind(deviceId, h5UserId, studentName);
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    @Override
    public RespEntity unbindDevice(Integer deviceId, Integer h5UserId) {
        int i = h5Mapper.unbindDevice(deviceId, h5UserId);
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    @Override
    public Long getCusTimeByCusId(Integer cusId) {
        return h5Mapper.getCusTimeByCusId(cusId);
    }

    @Override
    public int modifyPhoneByDeviceId(Integer deviceId, String phone) {
        return h5Mapper.modifyPhoneByDeviceId(deviceId, phone);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer synchronizationUserDevice(Integer userId, Integer deviceId, String studentName) {
        h5Mapper.unbindDeviceByDevice(deviceId);
        h5Mapper.unbindDeviceByUserId(userId);
        return h5Mapper.addBind(deviceId, userId, studentName);
    }

    @Override
    public H5User getH5UserById(Integer h5UserId) {
        return h5Mapper.getH5UserById(h5UserId);
    }

    @Override
    public Integer getCusIdByUserId(Integer userId) {
        return h5Mapper.getCusIdByUserId(userId);
    }
}
